import fs from 'fs';
import Promise from 'bluebird';

const readFile = Promise.promisify(fs.readFile);
const writeFile = Promise.promisify(fs.writeFile);

export const copyFile = (source, target, replacer) =>
  new Promise((resolve, reject) => {
    let cbCalled = false;
    async function done(err) {
      if (!cbCalled) {
        cbCalled = true;
        if (err) {
          reject(err);
        } else if (replacer) {
          let content = await readFile(target, 'utf8');
          content = replacer(content);
          await writeFile(target, content);
          resolve();
        } else {
          resolve();
        }
      }
    }

    const rd = fs.createReadStream(source);
    rd.on('error', err => done(err));
    const wr = fs.createWriteStream(target);
    wr.on('error', err => done(err));
    wr.on('close', err => done(err));
    rd.pipe(wr);
  });